//
//  SqliteDBMgr.cpp
//
//  Created by user on 12-5-15.
//  Copyright 2012 (网龙)DeNA. All rights reserved.
//

#include "GhSqliteDBMgr.h"
#include <string>

GhSqliteDBMgr* GhSqliteDBMgr::ms_pkSqliteMgr = 0;

GhSqliteDBMgr::GhSqliteDBMgr()
{

}

GhSqliteDBMgr::~GhSqliteDBMgr()
{
    GhSqliteDBMgr::destroyAll();
}

GhSqliteDb* GhSqliteDBMgr::createSqliteDb(const char* pszDbName)
{
    if (0 == pszDbName || !*pszDbName)
    {
        return 0;
    }
    
    GhSqliteDb* pkDb = new GhSqliteDb;
    addDb(pszDbName, pkDb);

    return pkDb;
}

GhSqliteDBMgr* GhSqliteDBMgr::sharedInstance()
{
    if (0 == ms_pkSqliteMgr)
    {
        ms_pkSqliteMgr = new GhSqliteDBMgr;
    }

    return ms_pkSqliteMgr;
}

void GhSqliteDBMgr::destroyInstance()
{
    if (ms_pkSqliteMgr)
    {
        delete ms_pkSqliteMgr;
        ms_pkSqliteMgr = 0;
    }
}

void GhSqliteDBMgr::destroyAll()
{
    for (SqliteDbMap::iterator it = m_kDbMap.begin(); it != m_kDbMap.end(); it++)
    {
        GhSqliteDb* pkDb = it->second;
        delete pkDb;
        pkDb = 0;
    }}

void GhSqliteDBMgr::addDb(const string& strName,GhSqliteDb* pkDb)
{
    pkDb->initDataBase(strName.c_str());
    m_kDbMap.insert(make_pair(strName, pkDb));
}

bool GhSqliteDBMgr::deleteDbByName(const char *pszName)
{
    return deleteDb(pszName);
}

bool GhSqliteDBMgr::deleteDbByPointer(GhSqliteDb *pkDb)
{
    if (0 == pkDb)
    {
        return false;
    }

    return deleteDb(pkDb->getName());
}

bool GhSqliteDBMgr::checkExistDb(const char* pszName)
{
    if (0 == pszName || !*pszName)
    {
        return false;
    }

    return false;
}

bool GhSqliteDBMgr::deleteDb(const char *pszName)
{
    if (0 == pszName || !*pszName)
    {
        return false;
    }

    GhSqliteDb* pkDb = 0;

    SqliteDbMap::iterator it = m_kDbMap.find(pszName);

    if (it == m_kDbMap.end())
    {
        return false;
    }

    pkDb = it->second;

    delete pkDb;
    pkDb = 0;

    m_kDbMap.erase(it);

    return true;
}